<?php

class WorkerController extends Controller
{

    /*
    * 根据经纬度获取附近工人列表分页
    *
    */
    public function actionGetNearlyWorkerListPaging()
    {

        try {
            //参数验证

            $lng = Util::getParamNotEmpty('lng');
            $lat = Util::getParamNotEmpty('lat');
            $page = Util::getParam("page","");
            $rows = Util::getParam("rows","");
            $tag = Util::getParam("tag","");

            //获取经纬度附近工人id
            $data = BaidulbsService::nearlydata($lng,$lat,$page,$rows,$tag);

            //根据id查找工人信息
            foreach($data->contents as $key => $value){
                $worker = Worker::model()->findByPK($value->worker_id);
                if(empty($worker) || $worker->is_delete ==1){
                    $data->contents[$key] = '此条数据已被清除';
                }else{
                    $value->workerinfo = WorkerService::formatWorker($worker);
                }

            }

            Util::responseObj($data);

            } catch (Exception $e) {
            Util::responseErrorMsg($e->getMessage());

        }


    }



    /*
     * 用户app
     *
     */
	public function actionGetWorkerList()
	{


        $sort_type = Util::getParamNotEmpty("sort_type");  //排序方式

        $type_id = Util::getParamNotEmpty("type_id");  //排序方式

        $lat = Util::getParamNotEmpty("lat");  //纬度

        $lng = Util::getParamNotEmpty("lng");  //经度


        //验证

         $work_type = WorkerTypes::model()->findByPK($type_id);
        Util::checkExistAndNotDelete($work_type);

        //服务内容


        $searchsql= Util::initSearchSql();

        $servicelist = WorkerServiceproj::model()->findAll($searchsql." and type_id = ".$type_id);







        $searchsql = Util::getSerarchStr($searchsql,"type_id","type_id");

        $searchsql = Util::getSerarchStrAdd($searchsql,"is_verify",MsgConst::WORKER_VERIFY_STATUS_VERIFIED);




        //获取count
        $totalcount = Worker::model()->count($searchsql);



        //排序
        //$searchsql = $searchsql." order by worker_id asc";
        $searchsql  = WorkerService::getOrderStr($searchsql,$sort_type);

        //加上分页控制
        $searchsql = Util::addLimitSql($searchsql);

        //获取list
        $list = Worker::model()->findAll($searchsql);

        //设置
        for($i=0;$i<count($list);$i++)
        {
            $worker = WorkerService::formatWorker($list[$i]);

            $worker->service_content = $servicelist;

            $worker->distance = WorkerService::calc_distance($lng,$lat,$worker->lng,$worker->lat);
        }



        // Util::responseObj(MsgConst::RETURN_SUCCESS);
        Util::responseList($totalcount,$list);


        Util::OutputArrayInJsonFormat(0,"success",$list);
	}

    /*
     * 工人端
     * 工人获取验证码
     */
    public function actionGetMsgCode()
    {
        try
        {
            //参数验证
            $mobile = Util::getParamNotEmpty("mobile");
            $type = Util::getParamNotEmpty("type");

            //输入合法性验证
            WorkerService::isVaildMobile($mobile);

            //短信类型验证
            SmsService::isVaildType($type,$mobile,MsgConst::APP_TYPE_WORKER);

            //失效该手机号之前所有验证短信
            SmsService::invaildMsg($mobile);

            //生成短信并发送
            $num = SmsService::getRandomNumber();
            SmsService::addNewSms($mobile,$num,$type);


            //返回数据
            Util::responseObj($num);


        }catch (Exception $e)
        {
            Util::responseErrorMsg($e->getMessage());

        }

    }

    /*
     * 工人端
     * 工人注册
     */
    public function actionRegister()
    {



        try {

            //参数验证
            $mobile = Util::getParamNotEmpty("mobile");
            $password = Util::getParamNotEmpty("password");
            $msg_code = Util::getParamNotEmpty("msg_code");

            //输入合法性验证
            WorkerService::isVaildMobile($mobile);
            WorkerService::islegalWorkerPasswod($password);

            //手机号是否注册
            $worker =  WorkerService::getWorkerByMobile($mobile);
            if(empty($worker)==false)
                throw new Exception("手机号已注册");

            //验证码验证
            SmsService::isVaildCode($mobile, $msg_code,MsgConst::SMS_TYPE_REGISTER_WORKER);



            //添加新用户
            WorkerService::addWorker($mobile,$password);

            //验证码失效
            SmsService::invaildMsg($mobile);



            //登录操作
            $worker = WorkerService::login($mobile,$password);


            //生成session
            $worker->session_id = SessionService::generateSession($worker->worker_id,MsgConst::SESSION_TYPE_WORKER);

            //返回数据
            Util::responseObj(WorkerService::formatWorker($worker));



            //返回数据
            Util::responseMsg(MsgConst::RETURN_SUCCESS);


        }catch (Exception $e)
        {
            Util::responseErrorMsg($e->getMessage());

        }




    }


    /*
     * 工人端
     * 工人登录
     */
    public function actionDoLogin()
    {

        try
        {
            //参数验证
            $mobile = Util::getParamNotEmpty("mobile");
            $password = Util::getParamNotEmpty("password");

            //输入合法性验证
            WorkerService::isVaildMobile($mobile);
            WorkerService::islegalWorkerPasswod($password);


            //登录操作
            $worker = WorkerService::login($mobile,$password);


            //生成session
            $worker->session_id = SessionService::generateSession($worker->worker_id,MsgConst::SESSION_TYPE_WORKER);

            //返回数据
            Util::responseObj(WorkerService::formatWorker($worker));


        }
        catch(Exception $e)
        {
            Util::responseErrorMsg($e->getMessage());

        }





    }


    /*
     * 工人端
     * 工人 验证码 登录
     */
    public function actionSmsLogin()
    {

        try
        {
            //参数验证
            $mobile = Util::getParamNotEmpty("mobile");
            $msg_code = Util::getParamNotEmpty("msg_code");

            //输入合法性验证
            WorkerService::isVaildMobile($mobile);



            //登录操作
            $worker = WorkerService::smsLogin($mobile,$msg_code);


            //生成session
            $worker->session_id = SessionService::generateSession($worker->worker_id,MsgConst::SESSION_TYPE_WORKER);

            //失效短信
            SmsService::invaildMsg($mobile);

            //返回数据
            Util::responseObj(WorkerService::formatWorker($worker));


        }
        catch(Exception $e)
        {
            Util::responseErrorMsg($e->getMessage());

        }





    }

    /*
     *
     * 工人端
     *登录界面-重置密码
     *
     */
    public function actionResetPassword()
    {
        //验证短信是否合法
        try {

            //参数验证
            $mobile = Util::getParamNotEmpty("mobile");
            $resetPassword = Util::getParamNotEmpty("resetPassword");
            $msg_code = Util::getParamNotEmpty("msg_code");

            WorkerService::isVaildMobile($mobile);
            WorkerService::islegalWorkerPasswod($resetPassword);

            //手机号是否存在
            $worker =  WorkerService::getWorkerByMobile($mobile);
            if(empty($worker)==true)
                throw new Exception("用户不存在");

            //验证手机号
            SmsService::isVaildCode($mobile, $msg_code,MsgConst::SMS_TYPE_RESET_WORKER);
            SmsService::invaildMsg($mobile);

            //将重置密码写入数据库
            WorkerService::changeUserPassword($resetPassword, $worker);
            //输出
            Util::responseMsg(MsgConst::RETURN_SUCCESS);


        }catch (Exception $e)
        {
            Util::responseErrorMsg($e->getMessage());

        }

    }

    /*
     * 工人段
    * 获取工人详情信息接口
    */
    public function actionGetWorkerInfo()
    {
        try
        {
            //登录验证
            $worker_id = SessionService::getUserIDBySessionid();

            //获取
            $worker = WorkerService::getWorkerByWorker_id($worker_id);

            $worker = WorkerService::formatidcard($worker);

            //输出
            Util::responseObj(WorkerService::formatWorker($worker));

        }
        catch (Exception $e)
        {
            Util::responseErrorMsg($e->getMessage());

        }

    }

    /*
     * 工人端
    * 获取工人详情信息接口
    */
    public function actionUpdateWorkerInfo()
    {
        try
        {
            //登录验证
            $worker_id = SessionService::getUserIDBySessionid();

            //参数验证
            $price = Util::getParamNotEmpty("price");

            $worker = WorkerService::changeWorkerInfo($worker_id,$price);



            //输出
            Util::responseObj(WorkerService::formatWorker($worker));

        }
        catch (Exception $e)
        {
            Util::responseErrorMsg($e->getMessage());

        }

    }



    /*
     * 工人端
     * 修改密码
     */
    public function actionChangePassword()
    {

        try
        {
            //参数验证
            $oldPassword = Util::getParamNotEmpty("oldPassword");
            $newPassword = Util::getParamNotEmpty("newPassword");

            //session_id 不为空
            $worker_id= SessionService::getUserIDBySessionid();
            $worker = WorkerService::getWorkerByWorker_id($worker_id);

            //新密码合法性
            WorkerService::islegalWorkerPasswod($newPassword);
            //旧密码验证
            WorkerService::isSamePasswod($oldPassword,$worker);
            //将新密码写入数据库
            WorkerService::changeUserPassword($newPassword, $worker);
            //返回数据
            Util::responseMsg(MsgConst::RETURN_SUCCESS);


        }
        catch(Exception $e)
        {
            Util::responseErrorMsg($e->getMessage());

        }
    }

    /*
     * 工人端
     * 提交认证审核
     */
    public function actionSendVerifyRequest()
    {
        Util::log_normal($this,"start");
        try
        {
            //登录验证
            $worker_id = SessionService::getUserIDBySessionid();

            //参数验证
            $avatar = Util::getParamNotEmpty("avatar");
            $idcard = Util::getParamNotEmpty("idcard");
            $real_name = Util::getParamNotEmpty("real_name");
            $pic_idcard = Util::getParamNotEmpty("pic_idcard");
            $type_id = Util::getParamNotEmpty("type_id");
            $work_year = Util::getParamNotEmpty("work_year");
            $price = Util::getParamNotEmpty("price");

            //合法性验证
            WorkerService::islegalIDCard($idcard);


            Util::log_normal($this,"合法性验证");



            //获取
            $worker = WorkerService::getWorkerByWorker_id($worker_id);

            //检验认证状态
            if($worker->is_verify == MsgConst::WORKER_VERIFY_STATUS_SUBMITING)
                throw new Exception("之前已经有认证请求在认证中，请稍候");

            if($worker->is_verify == MsgConst::WORKER_VERIFY_STATUS_VERIFIED)
                throw new Exception("您已认证成功");


            Util::log_normal($this,"检验认证状态".$type_id);

            //提交认证

            WorkerService::addNewVeirfy($worker,$avatar,$idcard,$pic_idcard,$real_name,$type_id,$work_year,$price);

            Util::log_normal($this,"提交认证".$type_id);
            //返回

            Util::responseMsg(MsgConst::RETURN_SUCCESS);







        } catch(Exception $e)
        {
            Util::responseErrorMsg($e->getMessage());

        }

    }

    /*
    * 工人端
    * 获取审核请求
    */
    public function actiongetVerifyRequest()
    {
        try
        {
            //登录验证
            $worker_id = SessionService::getUserIDBySessionid();

            //获取
            $worker = WorkerService::getWorkerByWorker_id($worker_id);

            //检验认证状态
            if($worker->is_verify == MsgConst::WORKER_VERIFY_STATUS_NOT_SUBMIT)
                throw new Exception("您还未提交审核");



            //提交认证

            $vrequest = WorkerVerifyRequestService::getRequestByWorkerid($worker_id);

            //返回

            Util::responseObj($vrequest);







        } catch(Exception $e)
        {
            Util::responseErrorMsg($e->getMessage());

        }

    }

    /*
     * 工人端
    * 工人删除图片
    *
    */
    public function actionDeleteConstructPic()
    {

        try {
            //检测
            $user_id = SessionService::getUserIDBySessionid();

            //参数验证
            $pic_url = Util::getParamNotEmpty("pic_url");


            //验证存在
            $obj = Worker::model()->findByPK($user_id);

            Util::checkExistAndNotDelete($obj);

            //检测图片是否已经存在

            $flag = strstr($obj->construct_pic_list,$pic_url);

            if($flag==false)
                throw new Exception("该图片未上传");

            //修改信息
            $arr = explode(',',$obj->construct_pic_list);

            $l = count($arr);

            $findpic = "";

            for($i=0;$i<$l;$i++)
            {
                $pic = $arr[$i];

                if($pic == $pic_url)
                    continue;
                else
                {
                    if(Util::IsEmpty($findpic))
                        $findpic= $pic;
                    else
                        $findpic = $findpic.",".$pic;
                }

            }


            $obj->construct_pic_list = $findpic;


            //保存
            Util::saveObjData($obj);


            //返回数据
            Util::responseMsg(MsgConst::RETURN_SUCCESS);


        } catch (Exception $e) {
            Util::responseErrorMsg($e->getMessage());

        }
    }

    /*
    * 工人端
   * 增加工人施工图片
   *
   */
    public function actionUploadConstructPic()
    {

        try {
            //检测
            $user_id = SessionService::getUserIDBySessionid();

            //参数验证
            $pic_url = Util::getParamNotEmpty("pic_url");


            //验证存在
            $obj = Worker::model()->findByPK($user_id);

            Util::checkExistAndNotDelete($obj);

            //检测图片是否已经存在

            if(strstr($obj->construct_pic_list,$pic_url)==true)
                throw new Exception("该图片已经上传");

            //修改信息

            if(Util::IsEmpty($obj->construct_pic_list))
                $obj->construct_pic_list = $pic_url;
            else
                $obj->construct_pic_list = $pic_url.",".$obj->construct_pic_list;

            //保存
            Util::saveObjData($obj);


            //返回数据
            Util::responseMsg(MsgConst::RETURN_SUCCESS);


        } catch (Exception $e) {
            Util::responseErrorMsg($e->getMessage());

        }
    }

    /*
    * 提现申请
    *
    */
    public function actionApplyWithdraw()
    {

        try {
            //检测
            $user_id = SessionService::getUserIDBySessionid();

            //参数验证
            $amount = Util::getParamNotEmpty("amount");
            $bank_name = Util::getParamNotEmpty("bank_name");
            $open_bank = Util::getParamNotEmpty("open_bank");
            $bankcard_no = Util::getParamNotEmpty("bankcard_no");


            //工人信息

            $worker = Worker::model()->findByPK($user_id);
            Util::checkExistAndNotDelete($worker);

            //检查是否满足最小提现金额
            if($amount < MsgConst::WITHDRAW_MIN_AMOUNT)
                throw new Exception("提现金额未达到最低提款额:".MsgConst::WITHDRAW_MIN_AMOUNT);


            //检查提现金额是否足够

            if($worker->balacan_cash < (double)$amount)
            {
                throw new Exception("可用余额不足，不能提现");
            }







            //发起提现请求
            WorkerAccountService::withdrawRequest($worker,$amount,$bank_name,$open_bank,$bankcard_no);



            //返回数据
            Util::responseMsg(MsgConst::RETURN_SUCCESS);


        } catch (Exception $e) {
            Util::responseErrorMsg($e->getMessage());

        }
    }

    /*
    * 获取现金流水列表
    *
    */
    public function actionGetBankCashList()
    {


        try {
            //参数验证

            //检测
            $user_id = SessionService::getUserIDBySessionid();


            //参数验证


            $searchsql = Util::initSearchSql();

            $searchsql = $searchsql." and worker_id = '".$user_id."'";


            //获取count
            $totalcount = WorkerBankcash::model()->count($searchsql);

            //排序
            $searchsql = $searchsql . " order by create_time desc";

            //加上分页控制
            $searchsql = Util::addLimitSql($searchsql);

            //获取list
            $list =WorkerBankcash ::model()->findAll($searchsql);


            Util::responseList($totalcount, $list);

        } catch (Exception $e) {
            Util::responseErrorMsg($e->getMessage());

        }
    }

    /*
    * 设备信息提交
    *
    */
    public function actionDeviceCheckIn()
    {

        try {
            //参数验证

            $device_id = Util::getParamNotEmpty("device_id");

            $device_info = Util::getParamNotEmpty("device_info");

            $version = Util::getParamNotEmpty("version");
            $app = Util::getParamNotEmpty("app");
            $platfrom = Util::getParamNotEmpty("platfrom");
            $obj_id = Util::getParamNotEmpty("obj_id");
            $lat = Util::getParamNotEmpty("lat");
            $lng = Util::getParamNotEmpty("lng");
            $channel_id = Util::getParamNotEmpty("channel_id");

            //是否存在
            $obj = GlDevice::model()->find("device_id='".$device_id."'");


            //事务开始
            $connection = Yii::app()->db;

            $transaction = $connection->beginTransaction();

            try {


                if (empty($obj)) {
                    //添加
                    $obj = new GlDevice();
                    // Util::initObjData($obj);
                    $obj->create_time = DateUtil::getNowTime();
                    $obj->update_time = DateUtil::getNowTime();
                    // $Obj->created_by = SessionService::getUserInfo();
                    $obj->is_delete = 0;
                    $obj->is_active = 0;

                } else {
                    // Util::recoverObjData($obj);
                }

                $obj->device_id = $device_id;
                $obj->device_info = $device_info;
                $obj->version = $version;
                $obj->app = $app;
                $obj->platfrom = $platfrom;
                $obj->obj_id = $obj_id;
                $obj->lat = $lat;
                $obj->lng = $lng;
                $obj->channel_id = $channel_id;



                Util::saveObjData($obj);


                //更新工人经纬度

                if($obj_id >0)
                {
                    $worker = Worker::model()->findByPK($obj_id);
                    Util::checkExistAndNotDelete($worker);


                    $worker->lat = $lat;
                    $worker->lng = $lng;

                    // Util::updateObjData($worker);

                    Util::saveObjData($worker);

                }

                //判断工人是否认证
                if($worker->is_verify == 1){
                    //更新百度云位置
                    BaidulbsService::upateWorkerLocation($lng,$lat,$worker->worker_id,$worker->real_name,$worker->type_name);
                }

                $transaction->commit();//事务结束



                //返回数据
                Util::responseMsg(MsgConst::RETURN_SUCCESS);


            } catch (Exception $e) {
                $transaction->rollback();//回滚函数

                throw new Exception($e->getMessage());

            }





        } catch (Exception $e) {
            Util::responseErrorMsg($e->getMessage());

        }
    }

    /*
    * 获取评价列表分页
    *
    */
    public function actionGetRatingList()
    {

        try {


            //检测
            //$user_id = SessionService::getUserIDBySessionid();


            //参数验证
            $worker_id = Util::getParamNotEmpty("worker_id");


            $searchsql = Util::initSearchSql();

            $searchsql = Util::getSerarchStrAdd($searchsql,"worker_id",$worker_id);


            //获取count
            $totalcount = OrderRating ::model()->count($searchsql);

                //排序
                $searchsql = $searchsql . " order by create_time desc";

                //加上分页控制
                $searchsql = Util::addLimitSql($searchsql);

                //获取list
                $list =OrderRating ::model()->findAll($searchsql);

                $l= count($list);

                for($i=0;$i<$l;$i++)
                {
                    $rating = $list[$i];
                    $user_id = $rating->user_id;

                    $user = UcUser::model()->findByPK($user_id);

                    if(empty($user)==false)
                        $rating->user = UserService::formatUser($user);
                }


                Util::responseList($totalcount, $list);

            } catch (Exception $e) {
            Util::responseErrorMsg($e->getMessage());

        }


    }

    /*
    * 定时更新百度lbs接口
    *
    */
    public function actionTimeupdate()
    {

        try {

            //获取验证过，没删除，有位置信息的工人列表
            $workerlist = Worker::model()->findAll("is_delete =0 and lat !='' and lng !='' and is_verify =1 order by create_time asc ");

            //更新百度云位置
            foreach($workerlist as $key => $value){
                BaidulbsService::upateWorkerLocation($value->lng,$value->lat,$value->worker_id,$value->real_name,$value->type_name);
            }

            //返回数据
            Util::responseMsg(MsgConst::RETURN_SUCCESS);


            } catch (Exception $e) {
            Util::responseErrorMsg($e->getMessage());

        }
    }


}